﻿using JESAI.Common.Util.Extensions;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Xml.Serialization;

namespace JESAI.Common.Util
{
    public static class XmlUtility
    {
        public static string FromXmlString<Type>(object obj)
        {

            try
            {
                MemoryStream Stream = new MemoryStream();
                XmlSerializer xml = new XmlSerializer(typeof(Type));
                //序列化对象  
                xml.Serialize(Stream, obj);
                Stream.Position = 0;
                StreamReader sr = new StreamReader(Stream);
                string str = sr.ReadToEnd();

                sr.Dispose();
                Stream.Dispose();
                return str;
            }
            catch (Exception ex)
            {

                throw;
            }



        }



        public static Stream FromXmlStream<Type>(object obj)
        {

            try
            {

                MemoryStream Stream = new MemoryStream();
                XmlSerializer xml = new XmlSerializer(typeof(Type));
                xml.Serialize(Stream, obj);
                Stream.Position = 0;
                StreamReader sr = new StreamReader(Stream);
                return sr.BaseStream;



            }
            catch (Exception ex)
            {

                throw ex;
            }



        }


        public static Type ToObject<Type>(string filePath) where Type : class
        {


            if (filePath.IsNullOrWhiteSpace())
            {
                throw new ArgumentNullException("filePath");
            }

            try
            {

                string xmlString = File.ReadAllText(filePath);
                if (xmlString.IsNullOrWhiteSpace())
                {
                    throw new Exception("读取xml失败");
                }
                using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(xmlString)))
                {

                    XmlSerializer serializer = new XmlSerializer(typeof(Type));
                    return serializer.Deserialize(stream) as Type;

                }
            }
            catch (Exception ex)
            {

                throw ex;
            }




        }

        private static ConcurrentDictionary<string, object> Cache = new ConcurrentDictionary<string, object>();
        /// <summary>
        /// 加载文件并转成对象
        /// </summary>
        /// <typeparam name="Type"></typeparam>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public static Type LoadFileToObject<Type>(string filePath) where Type : class, new()
        {


            if (Cache.ContainsKey(filePath))
            {
                object value = new object();
                if (Cache.TryGetValue(filePath, out value))
                {
                    return (Type)value;
                }
            }
            //var mapPath = HttpContext.Current.Request.MapPath("~/");
            var xmlFile = string.Format("{0}.xml", filePath);

            if (xmlFile.IsNullOrEmpty())
            {
                throw new Exception("没有找到对应配置文件");
            }
            var objectValue = ToObject<Type>(xmlFile);
            Cache.TryAdd(filePath, objectValue);
            return objectValue;
        }



        public static T Deserialize<T>(T t, string s)
        {
            using (StringReader sr = new StringReader(s))
            {
                XmlSerializer xz = new XmlSerializer(t.GetType());
                return (T)xz.Deserialize(sr);
            }
        }



        #region 反序列化
        /// <summary>  
        /// 反序列化  
        /// </summary>  
        /// <param name="type">类型</param>  
        /// <param name="xml">XML字符串</param>  
        /// <returns></returns>  
        public static object Deserialize(Type type, string xml)
        {
            try
            {
                using (StringReader sr = new StringReader(xml))
                {
                    XmlSerializer xmldes = new XmlSerializer(type);
                    return xmldes.Deserialize(sr);
                }
            }
            catch (InvalidOperationException)
            {

                return null;
            }
        }
        /// <summary>  
        /// 反序列化  
        /// </summary>  
        /// <param name="type"></param>  
        /// <param name="xml"></param>  
        /// <returns></returns>  
        public static object Deserialize(Type type, Stream stream)
        {
            XmlSerializer xmldes = new XmlSerializer(type);
            return xmldes.Deserialize(stream);
        }
        #endregion

        #region 序列化XML文件
        /// <summary>  
        /// 序列化XML文件  
        /// </summary>  
        /// <param name="type">类型</param>  
        /// <param name="obj">对象</param>  
        /// <returns></returns>  
        public static string Serializer(Type type, object obj)
        {
            MemoryStream Stream = new MemoryStream();
            //创建序列化对象  
            XmlSerializer xml = new XmlSerializer(type);
            try
            {
                //序列化对象  
                xml.Serialize(Stream, obj);
            }
            catch (InvalidOperationException)
            {
                throw;
            }
            Stream.Position = 0;
            StreamReader sr = new StreamReader(Stream);
            string str = sr.ReadToEnd();
            return str;
        }
        #endregion  
    }
}
